import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actionCreators } from './store';
import Topic from './components/Topic';
import List from './components/List';
import Recommend from './components/Recommend';
import Writer from './components/Writer';
import { BackTop } from './style';
import { 
  HomeWrapper,
  HomeLeft, 
  HomeRight 
} from './style';

class Home extends Component {

  handleScrollTop() {    
    window.scrollTo(0, 0);
  };

  componentDidMount() {
    this.props.changeHomeData();
    this.bindEvents();
  };

  componentWillUnmount() {
    window.removeEventListener('scroll', this.props.changeScrollTopShow);
  };

  render() {
    return (
      <HomeWrapper>
        <HomeLeft>
          <img className="banner-img" alt='主题' src="//upload.jianshu.io/admin_banners/web_images/4810/5c8f9017b3ce7b8f284c0527b84811e72dacc707.png?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540" />
          <Topic />
          <List />
        </HomeLeft>
        <HomeRight>
          <Recommend />
          <Writer />
        </HomeRight>
        {
          this.props.showScroll ? <BackTop onClick={this.handleScrollTop}>顶部</BackTop> : null
        }
      </HomeWrapper>
    );
  };

  bindEvents() {
    window.addEventListener('scroll', this.props.changeScrollTopShow);
  };
};

const mapState = (state) => ({
  showScroll: state.getIn(['home', 'showScroll'])
});

const mapDispatch = (dispatch) => ({
  changeHomeData() {
    dispatch(actionCreators.homeData())
  },
  changeScrollTopShow() {
    let heightTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (heightTop > 400) {
      dispatch(actionCreators.toggleTopShow(true))
    }else {
      dispatch(actionCreators.toggleTopShow(false))
    }
  }
});


export default connect(mapState, mapDispatch)(Home);